package org.lilred.nzbberry.http;

import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.device.api.util.StringUtilities;

import org.lilred.nzbberry.download.BlockingQueue;

public class FileChunkDownloader extends Thread implements FileTransferConnection {
	private BlockingQueue outputQueue = new BlockingQueue();
	String url;
	String connectionParameters;
	String contentType;
	long fileSize = -1;
	int responseCode;
	int state = -1;
	long progress = 0;
	
	public FileChunkDownloader(String url) {
		this.url = url;
		this.connectionParameters = HttpRequestDispatcher.getConnectionParameters();
		this.state = READY;
	}
	
	public BlockingQueue getOutputQueue() {
		return outputQueue;
	}
	
	public void run() {
		try {
			this.state = GETTING_HEADERS;
			HttpConnection connection = (HttpConnection) Connector.open(url + connectionParameters);
			connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            System.out.println("Download response code: " + responseCode);
            String contentType = connection.getHeaderField("Content-type");
            System.out.println("Download content-type: " + contentType);
            long size = connection.getLength();
            System.out.println("Download file size: " + size);
			String disposition = connection.getHeaderField("Content-Disposition");
			int start = disposition.indexOf("=") + 1;
			String filename = disposition.substring(start);
			filename = StringUtilities.removeChars(filename, "\"");
			this.state = TRANSFERRING;

			//This may not be necessary if it can accept archives.
			//if (disposition.indexOf(".nzb") == -1) throw new Exception("nzbBerry tried to open this URL because it looked like an nzb. However, the content-disposition header of the file indicates that it is not.  If this error is preventing you from downloading a file that you need, please uninstall nzbBerry."); 
            
            InputStream responseData = connection.openInputStream();
            byte[] chunk = new byte[512];
            int bytesRead = responseData.read(chunk);
            while (bytesRead > 0) {
            	outputQueue.push(chunk);
            	progress += bytesRead;
                bytesRead = responseData.read(chunk);
            }
            this.state = COMPLETE;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			this.state = ERROR;
		}
	}

	public long getLength() {
		return fileSize;
	}

	public long getProgress() {
		return progress;
	}

	public int getState() {
		return state;
	}
}
